<?php declare(strict_types=1);


namespace App\Controller;

use App\Common\Response;
use App\Service\FileService;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Middleware\AuthMiddleware;
use Psr\Http\Message\ResponseInterface;

/**
 * @Controller()
 */
class FileController  extends AbstractController
{
    /**
     * @Inject()
     * @var FileService
     */
    private FileService $fileService;

    /**
     * @RequestMapping(path="/upload",methods="post")
     * @Middlewares({
     *   @Middleware(AuthMiddleware::class)
     * })
     * @param RequestInterface $request
     * @param FileService $fileService
     * @return array|ResponseInterface
     * @throws Exception
     */
    public function upload(RequestInterface $request, FileService $fileService)
    {
        if(!$request->hasFile('file')){
            return Response::fail('没有文件被上传');
        }
        $file = $request->file('file');
        $filePath = $fileService->genFilePath($file->getBasename(),$file->getExtension());
        $file->moveTo($fileService::ROOT . $filePath);
        $user = $this->getUser();
        // 记录到文件数据库中
        $fileArray = $file->toArray();
        $attributes = [
            'created_by' => $user['stu_num'],
            'created_id' => $user['id'],
            'file_name' => $fileArray['name'],
            'class' => $user['class'],
            'path' => $filePath,
            'suffix' => $file->getExtension(),
            'size' => $file->getSize(),
        ];
        $fileModel = $this->fileService->recordTempFile($attributes);
        return $this->response->json(Response::success([
            'file'=> $fileModel->hash,
            'file_name' => $fileModel->file_name,
            'suffix' => $fileModel->suffix,
            'size' => $fileModel->size,
        ]));
    }


}